/* eslint-disable @typescript-eslint/no-use-before-define */
import UploadExcel from '@/components/uploadExcel';
import {
  delArticle,
  getArticles,
  updArticle,
  wordTakeEffective,
} from '@/services/ant-design-pro/knowledge';
import { DataType } from '@/services/models/dataDoc';
import {
  DownCircleOutlined,
  FileAddOutlined,
  SearchOutlined,
  UpCircleOutlined,
  UploadOutlined,
} from '@ant-design/icons';
import { history } from '@umijs/max';
import {
  Badge,
  Button,
  Card,
  Form,
  FormInstance,
  Input,
  InputRef,
  message,
  Popconfirm,
  Space,
  Table,
  Tabs,
  TabsProps,
} from 'antd';
// import type { ColumnsType } from 'antd/es/table';
import { toNumber } from 'lodash';
import debounce from 'lodash/debounce';
import moment from 'moment';
import React, { useCallback, useContext, useEffect, useRef, useState } from 'react';
import { flushSync } from 'react-dom';
import styles from './index.less';
import './style.less';

const EditableContext = React.createContext<FormInstance<any> | null>(null);

interface EditableRowProps {
  index: number;
}

const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
  console.log(index);
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

interface EditableCellProps {
  title: React.ReactNode;
  editable: boolean;
  children: React.ReactNode;
  dataIndex: keyof DataType;
  record: DataType;
  handleSave: (record: DataType) => void;
}

const EditableCell: React.FC<EditableCellProps> = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef<InputRef>(null);
  const form = useContext(EditableContext)!;

  useEffect(() => {
    if (editing) {
      inputRef.current!.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({ [dataIndex]: record[dataIndex] });
  };

  const save = async () => {
    try {
      const values = await form.validateFields();

      toggleEdit();

      const res = await updArticle(record.article_id, values.question);
      if (res.code === 0) {
        handleSave({ ...record, ...values });
      } else {
        message.error(res.msg);
      }
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };

  let childNode = children;

  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{ margin: 0 }}
        name={dataIndex}
        rules={[
          {
            required: true,
            message: `${title} is required.`,
          },
        ]}
      >
        <Input.TextArea ref={inputRef} onPressEnter={save} onBlur={save} autoSize={true} />
      </Form.Item>
    ) : (
      <div className="editable-cell-value-wrap" style={{ paddingRight: 24 }} onClick={toggleEdit}>
        {children}
      </div>
    );
  }

  return <td {...restProps}>{childNode}</td>;
};

type EditableTableProps = Parameters<typeof Table>[0];

type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;

const DataQuestion: React.FC = () => {
  const [activeKey, setActiveKey] = useState<string>('1');
  const [isOpenExcel, setIsOpenExcel] = useState<boolean>(false);
  const [dataSource, setDataSource] = useState<DataType[]>([]);
  const [totals, setTotals] = useState<number>();
  const [knowledgeId, setKnowledgeId] = useState<string>('');
  const [searchTerm, setSearchTerm] = useState<string>('');
  //分页默认值，
  const [pageOption, setPageOption] = useState({
    pageNo: 1, //当前页为1
    pageSize: 10, //一页10行
  });

  const deleteRow = async (delIndex: number) => {
    const { article_id } = dataSource[delIndex];
    const res = await delArticle(article_id);
    if (res.code === 0) {
      if (dataSource?.length === 1) {
        if (pageOption.pageNo > 1) {
          paginationChange(pageOption.pageNo - 1, pageOption.pageSize);
        } else {
          setDataSource([]);
        }
      } else {
        articleRes(pageOption.pageNo, pageOption.pageSize, activeKey, searchTerm);
      }
    } else {
      message.error(res.msg);
    }
  };

  const updateRow = async (row: DataType) => {
    const params = {
      effective: '1',
      article_id: row.article_id,
    };
    const res = await wordTakeEffective(params);
    if (res.code === 0) {
      if (dataSource?.length === 1) {
        if (pageOption.pageNo > 1) {
          paginationChange(pageOption.pageNo - 1, pageOption.pageSize);
        } else {
          setDataSource([]);
        }
      } else {
        articleRes(pageOption.pageNo, pageOption.pageSize, activeKey, searchTerm);
      }
    } else {
      message.error(res.msg);
    }
  };

  const defaultColumns: (ColumnTypes[number] & { editable?: boolean; dataIndex: string })[] = [
    {
      title: '序号',
      dataIndex: 'index',
      width: 60,
      render: (_text: string, _record: any, index: number) =>
        `${(pageOption.pageNo - 1) * pageOption.pageSize + (index + 1)}`,
    },
    {
      title: '问题',
      dataIndex: 'question',
      editable: activeKey === '2' ? true : false,
    },
    Table.EXPAND_COLUMN,
    {
      title: '状态',
      dataIndex: 'effective',
      width: 100,
      render: (_, record: any) => {
        if (record.effective) {
          return <Badge status="success" text={'已入库'} />;
        } else {
          return <Badge text={'待入库'} color={'orange'} />;
        }
      },
    },
    {
      title: '上传时间',
      dataIndex: 'created_at',
      width: 180,
      sorter: (a: any, b: any) => a.created_at - b.created_at,
      render: (_: any, record: any) =>
        `${moment(parseInt(record.created_at)).format('YYYY-MM-DD HH:mm:ss')}`,
    },
    {
      title: '上传人',
      dataIndex: 'created_by',
      width: 140,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 120,
      render: (_, record: any, index) => (
        <Space>
          <Popconfirm title="确定删除?" onConfirm={() => deleteRow(index)}>
            <a>删除</a>
          </Popconfirm>
          {!record.effective && (
            <Popconfirm title="确定入库?" onConfirm={() => updateRow(record)}>
              <a>入库</a>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };

  const columns = defaultColumns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: DataType) => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        handleSave,
      }),
    };
  });

  const handleSave = (row: DataType) => {
    const newData = [...dataSource];
    const index = newData.findIndex((item) => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    setDataSource(newData);
  };

  const debounceSave = useCallback(
    debounce(async (params: any) => {
      articleRes(1, pageOption.pageSize, params.activeKey, params.searchKey, params.kId);
    }, 1000),
    [],
  );

  const articleRes = async (
    current: number,
    size: number,
    type: string,
    searchKey?: string,
    kId?: string,
  ) => {
    let params: any = { page: current, per_page: size, effective: type === '1' ? 1 : 0 };
    if (kId) {
      params.knowledge_base_id = toNumber(kId);
    } else {
      if (knowledgeId) {
        params.knowledge_base_id = toNumber(knowledgeId);
      } else {
        params.knowledge_base_id = 0;
      }
    }

    if (searchKey) {
      params.search_term = searchKey;
    }
    console.log(params);
    const res = await getArticles(params);
    if (res.code === 0) {
      const { articles, total_count } = res.data;
      setTotals(total_count);
      articles.forEach((article: any) => {
        article.key = +new Date() + Math.random();
      });
      setDataSource(articles);
    } else {
      message.error(res.msg);
    }
    return;
  };

  useEffect(() => {
    const query = history.location.search;
    if (query) {
      const kbid = query.split('?')[1].split('=')[1];
      flushSync(() => {
        setKnowledgeId(kbid);
      });
    } else {
      articleRes(pageOption.pageNo, pageOption.pageSize, activeKey);
    }
  }, []);

  useEffect(() => {
    if (knowledgeId) {
      articleRes(pageOption.pageNo, pageOption.pageSize, activeKey, searchTerm);
    }
  }, [knowledgeId]);

  const updateOpenExcel = (open: boolean) => {
    setIsOpenExcel(open);
    articleRes(pageOption.pageNo, pageOption.pageSize, activeKey, searchTerm);
  };

  const tableSize = () => {
    return {
      width: (window.screen.availWidth * 1054) / 1440.0,
      height: (window.screen.availHeight * 500) / 810.0,
      padding: (window.screen.availWidth - (window.screen.availWidth * 1054) / 1440.0) / 2,
    };
  };

  const searchTermChange = (e: any) => {
    const searchKey = e.target.value;
    setSearchTerm(searchKey);
    setPageOption({
      pageNo: 1, //当前页为1
      pageSize: 10, //一页10行
    });
    const params = { searchKey, kId: knowledgeId, activeKey };
    debounceSave(params);
  };

  //分页配置
  const paginationProps = {
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: () => `共${totals}条`,
    current: pageOption.pageNo,
    pageSize: pageOption.pageSize,
    total: totals,
    // eslint-disable-next-line @typescript-eslint/no-use-before-define
    onChange: (current: number, size: number) => paginationChange(current, size),
  };

  //当翻页时，改变当前为第current页，current和size这两参数是onChange API自带的，会帮你算出来你现在在第几页，这一页有多少行数据。
  const paginationChange = async (current: number, size: number) => {
    //前面用到useState
    setPageOption({
      pageNo: current, //当前所在页面
      pageSize: size, //一页有几行
    });

    articleRes(current, size, activeKey);
  };

  const rowClassName = (record: any, index: any) => {
    let className = styles['light-row'];
    if (index % 2 === 1) className = styles['dark-row'];
    return className;
  };

  const items: TabsProps['items'] = [
    {
      key: '1',
      label: `已入库`,
      children: (
        <Card style={{ width: tableSize().width }}>
          <Table
            components={components}
            columns={columns as ColumnTypes}
            className={'custom-table-style'}
            dataSource={dataSource}
            expandable={{
              expandedRowRender: (record: any) => (
                <div className={styles.detailCon}>{record.content}</div>
              ),
              expandIcon: ({ expanded, onExpand, record }) =>
                expanded ? (
                  <UpCircleOutlined onClick={(e) => onExpand(record, e)} />
                ) : (
                  <DownCircleOutlined onClick={(e) => onExpand(record, e)} />
                ),
            }}
            rowClassName={rowClassName}
            pagination={paginationProps}
            scroll={{ y: tableSize().height }}
            size="small"
          />
        </Card>
      ),
    },
    {
      key: '2',
      label: `待入库`,
      children: (
        <Card style={{ width: tableSize().width }}>
          <Table
            components={components}
            columns={columns as ColumnTypes}
            className={'custom-table-style'}
            dataSource={dataSource}
            expandable={{
              expandedRowRender: (record: any) => (
                <div className={styles.detailCon}>{record.content}</div>
              ),
              expandIcon: ({ expanded, onExpand, record }) =>
                expanded ? (
                  <UpCircleOutlined onClick={(e) => onExpand(record, e)} />
                ) : (
                  <DownCircleOutlined onClick={(e) => onExpand(record, e)} />
                ),
            }}
            rowClassName={rowClassName}
            pagination={paginationProps}
            scroll={{ y: tableSize().height }}
            size="small"
          />
        </Card>
      ),
    },
  ];

  const initResParams = () => {
    setSearchTerm('');
    setDataSource([]);
    setPageOption({
      pageNo: 1, //当前页为1
      pageSize: 10, //一页10行
    });
  };

  const tabChange = (e: any) => {
    flushSync(() => {
      setActiveKey(e);
    });
    initResParams();
    articleRes(1, 10, e, '');
  };

  return (
    <div className="page-container">
      {/* <Header title={'知识库'}></Header> */}
      <div className={styles.containData}>
        <div className={styles.header} style={{ right: tableSize().padding }}>
          {/* <span style={{ fontWeight: 500 }}>数据库</span> */}
          <div style={{ display: 'flex', flexDirection: 'row' }}>
            <Input
              value={searchTerm}
              className="searchBox"
              prefix={<SearchOutlined style={{ color: '#D0D0D0' }} />}
              placeholder="请输入需要搜索的内容"
              onChange={(e) => searchTermChange(e)}
            ></Input>
            {activeKey === '1' && (
              <Button className={styles.upload} onClick={() => setIsOpenExcel(true)}>
                <UploadOutlined />
                批量上传
              </Button>
            )}
            {activeKey === '2' && (
              <Button className={styles.upload} onClick={() => setIsOpenExcel(true)}>
                <FileAddOutlined />
                语料上传
              </Button>
            )}
          </div>
        </div>
        <Tabs defaultActiveKey="1" items={items} activeKey={activeKey} onChange={tabChange}></Tabs>
        {isOpenExcel && (
          <UploadExcel
            knowledgeId={knowledgeId}
            updateOpenExcel={updateOpenExcel}
            open={isOpenExcel}
            type={activeKey}
          ></UploadExcel>
        )}
      </div>
    </div>
  );
};

export default DataQuestion;
